﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace BlogAppExt.Models
{
    /// <summary>
    /// View Model class for generating search results and sending them to the user
    /// </summary>
    public class SearchVM
    {
        //public List<BlogPost> Posts { get; set; }
        public List<BlogItem> ResultsPosts { get; set; }
        public string SearchString { get; set; }

        public SearchVM()
        {
            //Posts = new List<BlogPost>();
            ResultsPosts = new List<BlogItem>();
        }

        /// <summary>
        /// Generates a list of search results based on the provided search string, BlogPost list, and CommentPost list
        /// </summary>
        /// <param name="searchString">The string to search for in the posts</param>
        /// <param name="posts">A list of BlogPost objects to search</param>
        /// <param name="comments">A list of CommentPost objects to search</param>
        public SearchVM(string searchString, List<BlogPost> posts, List<CommentPost> comments)
        {
            RunSearch(searchString, posts, comments);
        }

        /// <summary>
        /// Generates a list of search results based on the provided search string, BlogPost list, and CommentPost list
        /// </summary>
        /// <param name="searchString">The string to search for in the posts</param>
        /// <param name="posts">A list of BlogPost objects to search</param>
        /// <param name="comments">A list of CommentPost objects to search</param>
        public void RunSearch(string searchString, List<BlogPost> posts, List<CommentPost> comments)
        {
            SearchString = searchString;
            List<BlogPost> resultsPosts = posts.Where(x => x.Title.ToLower().Contains(SearchString.ToLower()) || x.Text.ToLower().Contains(SearchString.ToLower())).ToList();

            List<CommentPost> resultsComments = comments.Where(x => x.Title.ToLower().Contains(SearchString.ToLower()) || x.Text.ToLower().Contains(SearchString.ToLower())).ToList();

            ResultsPosts.AddRange(resultsPosts);
            ResultsPosts.AddRange(resultsComments);
            ResultsPosts = ResultsPosts.OrderBy(x => x.PostDate).ToList();

        }
    }
}